// 引入 axios
import store from "@/store";
import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import { getToken, removeToken, setToken, getSID } from "@/utils/auth";
import { getParamsDatas } from "@/utils/sid";
const BASE_URL = process.env.BASE_URL; //环境区分
//获取路由参数
// function getParamsDatas(str) {

//     var arr = str.split('?')

//     if (arr.length == 2) {
//         var data = arr[1].split('&')
//         var obj = {}
//         data.forEach(function (item) {
//             var params = item.split('=')

//             obj[params[0]] = params[1]
//         })
//         return {
//             url: arr[0], //url
//             data: obj    //参数
//         }
//     } else {
//         return {
//             url: arr[0], //无参数,
//             data: {}
//         }
//     }
//   }
//获取路由参数
const sid = getParamsDatas(location.href).data.soleId;
// console.log(sid)
// console.log('location.href',getParamsDatas( location.href))
// 文档开发环境
// 本机
// let api = "http://192.168.11.148:8098/"; //健源
// let api = 'http://192.168.3.190:8098/';//思宇
// let api = "http://192.168.11.193:8098/"; //睿祺
// let api = "http://192.168.17.3:8090/"; //佳铭
// let api = '/api'
//服务器地址
// let api = "https://127.0.0.1:8098/";
// let api = 'http://219.135.214.198:8090/'//百度
let api = "https://ibms.on-bright.com:8000/"; //昂宝外网
// let api = 'http://192.168.1.106:8098/';//昂宝内网

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: api,
    // 超时
    timeout: 30000,
});

// axios 配置
service.interceptors.response.use(
    (response) => {
        // console.log('response', response)
        return response.status == 200 ? response : response;
    },
    function (error) {
        // 请求失败、错误处理回调
        //console.log(error);
        var errorText = error + "";
        if (errorText.indexOf("Network Error") != -1) {
            Message.error({
                message: "服务器接口数据连接失败！" + error,
            });
        }
    }
);
var sessionId = "user1612382328928";
setToken(sessionId);

// 请求拦截 设置token
service.interceptors.request.use((config) => {
    // console.log('error~~~~~',config);
    // 设置请求头

    config.headers.Authorization = getToken();
    config.headers["token"] = getToken();
    config.headers.__sid = sid;
    // config.headers.__sid = "3902d188-9051-47c0-9abe-bcc9787790e5";
    // this.$cookies.get()
    // console.log('this.$cookies.get(sid)', this.$cookies.get())
    return config;
});

// 是否显示重新登录
export let isRelogin = { show: false };
let errorCode = {
    401: "认证失败，无法访问系统资源",
    403: "当前操作没有权限",
    404: "访问资源不存在",
    default: "系统未知错误，请反馈给管理员",
};
// 响应拦截器
service.interceptors.response.use((res) => {
    // 未设置状态码则默认成功状态
    const code = res?.data.code || "200";
    // console.log('res.data ', res.data)
    // 获取错误信息
    const msg = errorCode[code] || res?.data?.msg || errorCode["default"];
    // console.log('msg',msg)
    // 二进制数据则直接返回
    if (
        res?.request?.responseType === "blob" ||
        res?.request.responseType === "arraybuffer"
    ) {
        return res?.data;
    } else {
        if (code === "401") {
            if (!isRelogin.show) {
                isRelogin.show = true;
                MessageBox.confirm(
                    "登录状态已过期，您可以继续留在该页面，或者重新登录",
                    "系统提示",
                    {
                        confirmButtonText: "重新登录",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        isRelogin.show = false;
                        store.dispatch("LogOut").then(() => {
                            // 跳转到首页
                            location.href = "/message/index";
                        });
                    })
                    .catch(() => {
                        isRelogin.show = false;
                    });
            }
        } else if (code === "500") {
            Message({
                message: res.data.msg,
                type: "error",
            });
            return false;
        } else if (code !== "200") {
            Notification.error({
                title: msg,
            });
        } else {
            return res;
        }
    }
});

// 封装一个get 请求
let getRequest = (url) => {
    return new Promise((resolve, reject) => {
        service.get(url).then((res) => {
            resolve(res);
        });
    });
};

let postRequest = (url, data) => {
    return new Promise((reslove, resject) => {
        service.post(url, data).then((res) => {
            reslove(res);
        });
    });
};

let putRequest = (url, data) => {
    return new Promise((reslove, resject) => {
        service.put(url, data).then((res) => {
            reslove(res);
        });
    });
};

let deleteRequest = (url) => {
    return new Promise((reslove, resject) => {
        service.delete(url).then((res) => {
            reslove(res);
        });
    });
};

let windowOpen = (data) => {
    return window.open(api + data, "_blank");
};

export { getRequest, postRequest, putRequest, deleteRequest, api, windowOpen };
